<?php
/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
 */

defined('IN_IA') or exit('Access Denied');
error_reporting(0);
//全局变量
global $_GPC;
$do = in_array($do, array('getsessionkey', 'authlogin','getQuestion','getQuestion2','postScore','getUserCount','getUserInfo')) ? $do : 'index';
if($do=='getsessionkey'){

	$appid = 'wx20ed65cbd26fe73b';
	$secret = 'ea2f5e06c90b9967a4fd9f3e8ae48c2c';

	$code = trim($_POST['code']);
	if (!$code) {
		echo json_encode(array('status'=>0,'err'=>'非法操作！'));
		exit();
	}

	if (!$appid || !$secret) {
		echo json_encode(array('status'=>0,'err'=>'非法操作！'.__LINE__));
		exit();
	}
	//保存openid到緩存


	$get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$get_token_url);
	curl_setopt($ch,CURLOPT_HEADER,0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
	$res = curl_exec($ch);
	curl_close($ch);
	$_SESSION['min_info'] = json_decode($res,true);
	echo $res;
	exit();
}
if($do=='authlogin'){

	$openid = $_POST['openid'];
	if (!$openid) {
		echo json_encode(array('status'=>0,'err'=>'授权失败！'.__LINE__));
		exit();
	}

	$userinfo = pdo_fetch("SELECT * FROM " . tablename('fighting_user') . " WHERE `openid`=:openid  LIMIT 1" ,array (':openid' => $openid ));

	if (!$userinfo) {

		$data = array();
		$data['weid'] = 21;
		$data['fid'] = 17;
		$data['type'] = 2;
		$data['nickname'] = $_POST['nickname'];
		$data['sex'] = $_POST['gender'];
		$data['openid'] = $openid;
		$data['thumb'] = $_POST['HeadUrl'];
		$data['create_time'] = time();

		pdo_insert('fighting_user', $data);

		exit();
	}
}
if($do=='getUserInfo'){
    $openid = $_GET['openid'];
    if (!$openid) {
        echo json_encode(array('status'=>0,'err'=>'授权失败！'.__LINE__));
        exit();
    }
    $userinfo = pdo_fetch("SELECT * FROM " . tablename('fighting_user') . " WHERE `openid`=:openid  LIMIT 1" ,array (':openid' => $openid ));

    if($userinfo){
        $dtcount = pdo_fetchcolumn("select count(*) FROM " . tablename('fighting') . " where from_user=:from_user", array(":from_user" => $openid));
        $number = pdo_fetchcolumn("select count(*) FROM " . tablename('fighting') . " where from_user=:from_user and begin_time<=:begin_time and begin_time>=:end_time", array(":from_user" => $openid,":begin_time"=>time(),":end_time"=>strtotime("-7 days")));

        $returndata = json_encode(array('status'=>1,'err'=>'获取成功','dtnumber'=>$dtcount,'number'=>$number));
    }else{
        $returndata = json_encode(array('status'=>0,'err'=>'获取成功'));
    }

    echo $returndata;
}
if($do=='getQuestion'){

	//$openid = $_POST['openid'];
	$weid = 21;
	$id = $_POST['id'];
    $nocache = $_GET['nocache'];
	/*if(!$openid ){
		echo json_encode(array('status'=>0,'err'=>'授权失败！'.__LINE__));
		exit();
	}*/
    load()->func('cache');
    $api = cache_load("question.json");


    //判断活动是否配置
    $flight_setting = pdo_fetch("SELECT * FROM " . tablename('fighting_setting') . " WHERE id = '$id' LIMIT 1");
    if (empty($flight_setting)) {
        echo json_encode(array('status'=>0,'err'=>'非法访问'.__LINE__));
        exit();
    }
    //查看之前是否有未提交的答题（避免意外退出后重复抽题）
    //$re = pdo_fetch("SELECT * FROM " . tablename('fighting') . " WHERE status=0 and `ip`=:ip AND `fid`={$id} order by id desc", array (':ip' => CLIENT_IP ));
    //初始化数据
    $num = 1;
    $questions = [];
    $time = $flight_setting['answertime'];
    $cachearr = cache_load("question.arr");
    if($cachearr && empty($nocache)){
        $qdata = $cachearr;
    }else{
        //获取题目列表
        $result = pdo_fetchall('SELECT * FROM '.tablename('fighting_question_bank').' WHERE sid=:sid',array(':sid' => $id));
        $qdata = array();
        //随机抽取题目
        foreach ($result as $k=>$v){
            $qdata[$v['type']][]=$v;
        }
        cache_write("question.arr", $qdata);
    }

    foreach ($qdata as $k=>$v){
        $ts[$k] = array_rand($v, $flight_setting['qnum']);
        //打乱题目
        shuffle($ts[$k]);
    }

    foreach ($ts as $t=>$a){
        //处理题目
        if($t==1){

        }
        foreach($a as $k=>$tmp) {
            $questions[$t][$k+1] = $qdata[$t][$tmp];
        }

        foreach ($questions[$t] as $k => $v) {
            $answer = array();
            if(!empty($v['optionA'])){
                $v['optionA'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionA']);
                $answer[] = array('code'=>"A",'value'=>trim($v['optionA']));
            }
            if(!empty($v['optionB'])){
                $v['optionB'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionB']);
                $answer[] = array('code'=>"B",'value'=>trim($v['optionB']));
            }
            if(!empty($v['optionC'])){
                $v['optionC'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionC']);
                $answer[] = array('code'=>"C",'value'=>trim($v['optionC']));
            }
            if(!empty($v['optionD'])){
                $v['optionD'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionD']);
                $answer[] = array('code'=>"D",'value'=>trim($v['optionD']));
            }
            if(!empty($v['optionE'])){
                $v['optionE'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionE']);
                $answer[] = array('code'=>"E",'value'=>trim($v['optionE']));
            }
            if(!empty($v['optionF'])){
                $v['optionF'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionF']);
                $answer[] = array('code'=>"F",'value'=>trim($v['optionF']));
            }

            $option[$t][$v['id']] = $answer;

            //$questions[$t][$k+1]['question'] = trim($v['question']);
        }
    }
    $returndata = json_encode(array('status'=>1,'err'=>'获取成功','flight'=>$flight_setting,'question'=>$questions,'option'=>$option));


	echo $returndata;
}
if($do=='getQuestion2'){

    //$openid = $_POST['openid'];
    $weid = 21;
    $id = $_POST['id'];
    $nocache = $_GET['nocache'];
    /*if(!$openid ){
        echo json_encode(array('status'=>0,'err'=>'授权失败！'.__LINE__));
        exit();
    }*/
    load()->func('cache');
    $api = cache_load("question.json");

    //判断活动是否配置
    $flight_setting = pdo_fetch("SELECT * FROM " . tablename('fighting_setting') . " WHERE id = '$id' LIMIT 1");
    if (empty($flight_setting)) {
        echo json_encode(array('status'=>0,'err'=>'非法访问'.__LINE__));
        exit();
    }
    //查看之前是否有未提交的答题（避免意外退出后重复抽题）
    //$re = pdo_fetch("SELECT * FROM " . tablename('fighting') . " WHERE status=0 and `ip`=:ip AND `fid`={$id} order by id desc", array (':ip' => CLIENT_IP ));
    //初始化数据
    $num = 1;
    $questions = [];
    $time = $flight_setting['answertime'];
    $cachearr = cache_load("question.arr");
    if($cachearr && empty($nocache)){
        $qdata = $cachearr;
    }else{
        //获取题目列表
        $result = pdo_fetchall('SELECT * FROM '.tablename('fighting_question_bank').' WHERE sid=:sid',array(':sid' => $id));
        $qdata = array();
        //随机抽取题目
        foreach ($result as $k=>$v){
            $qdata[$v['type']][]=$v;
        }
        cache_write("question.arr", $qdata);
    }

    foreach ($qdata as $k=>$v){
        if($k==1){
            $ts[$k] = array_rand($v, 10);
        }else{
            //$ts[$k] = array_rand($v, 3);
        }

        //打乱题目
        shuffle($ts[$k]);
    }

    foreach ($ts as $t=>$a){
        //处理题目
        if($t==1){

        }
        foreach($a as $k=>$tmp) {
            $questions[$t][$k+1] = $qdata[$t][$tmp];
        }

        foreach ($questions[$t] as $k => $v) {
            $answer = array();
            if(!empty($v['optionA'])){
                $v['optionA'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionA']);
                $answer[] = array('code'=>"A",'value'=>trim($v['optionA']));
            }
            if(!empty($v['optionB'])){
                $v['optionB'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionB']);
                $answer[] = array('code'=>"B",'value'=>trim($v['optionB']));
            }
            if(!empty($v['optionC'])){
                $v['optionC'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionC']);
                $answer[] = array('code'=>"C",'value'=>trim($v['optionC']));
            }
            if(!empty($v['optionD'])){
                $v['optionD'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionD']);
                $answer[] = array('code'=>"D",'value'=>trim($v['optionD']));
            }
            if(!empty($v['optionE'])){
                $v['optionE'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionE']);
                $answer[] = array('code'=>"E",'value'=>trim($v['optionE']));
            }
            if(!empty($v['optionF'])){
                $v['optionF'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionF']);
                $answer[] = array('code'=>"F",'value'=>trim($v['optionF']));
            }

            $option[$t][$v['id']] = $answer;

            //$questions[$t][$k+1]['question'] = trim($v['question']);
        }
    }
    $flight_setting['type'][1]=10;
    //$flight_setting['type'][3]=3;
    $returndata = json_encode(array('status'=>1,'err'=>'获取成功','flight'=>$flight_setting,'question'=>$questions,'option'=>$option));


    echo $returndata;
}
if($do=='postScore') {

    $openid = $_POST['openid'];
    $score = $_POST['score'];
    $address = $_POST['address'];
    $nickName = $_POST['nickName'];
    $longitude = $_POST['longitude'];
    $latitude = $_POST['latitude'];
    $weid = 21;
    $id = 17;
    if (!$openid) {
        echo json_encode(array('status' => 0, 'err' => '授权失败！' . __LINE__));
        exit();
    }
    $insert['fid'] = $id;
    $insert['weid'] = $weid;
    $insert['ip'] = CLIENT_IP;
    $insert['begin_time'] = time();
    $insert['score'] = $score;
    $insert['nickName'] = $nickName;
    $insert['address'] = $address;
    $insert['from_user'] = $openid;
    $insert['latitude'] = $latitude;
    $insert['longitude'] = $longitude;
    pdo_insert('fighting', $insert);
}

if($do=='getUserCount') {

    $data = pdo_fetch("SELECT count(*) as tp_count FROM " . tablename('fighting') . " WHERE weid=21");

    echo  json_encode(array('status'=>1,'err'=>'获取成功','count'=>$data['tp_count']));
}


